﻿using System;
using System.Collections.Generic;

namespace Athena.Convertible.Implementations
{
    using ExceptionHandler;
    /// <summary>
    /// 默认类型转换服务
    /// </summary>
    public class DefaultTypeConvertibleService : ITypeConvertibleService
    {
        private readonly IEnumerable<TypeConvertDelegate> _typeConvertDelegates;
        public DefaultTypeConvertibleService(ITypeConvertibleProvider typeConvertibleProvider)
        {
            _typeConvertDelegates = typeConvertibleProvider.CreateConverts();
        }

        /// <summary>
        /// 类型转换
        /// </summary>
        /// <param name="instance"></param>
        /// <param name="conversionType"></param>
        /// <returns></returns>
        public object Convert(object instance, Type conversionType)
        {
            object result = null;
            foreach (var convert in _typeConvertDelegates)
            {
                result = convert(instance, conversionType);
                if (result != null)
                {
                    return result;
                }
            }
            if (result != null)
            {
                return result;
            }
            throw new RpcConvertException($"无法将实例:{instance}转换为{conversionType}类型。", null);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="instance"></param>
        /// <returns></returns>
        public T Convert<T>(object instance)
        {
            return (T)Convert(instance, typeof(T));
        }
    }
}
